/**
 * 质量卡点系统 - 实时验证每个Phase的输出质量
 */

export interface QualityGateConfig {
  phase: number;
  name: string;
  requiredMetrics: QualityMetric[];
  blockingThreshold: number;
  warningThreshold: number;
}

export interface QualityMetric {
  name: string;
  weight: number;
  calculator: (input: any) => Promise<number>;
  threshold: {
    blocking: number;  // 低于此值阻止进入下一Phase
    warning: number;   // 低于此值发出警告
  };
}

export interface QualityGateResult {
  phase: number;
  success: boolean;
  score: number;
  metrics: MetricResult[];
  blockers: QualityIssue[];
  warnings: QualityIssue[];
  recommendations: string[];
  canProceed: boolean;
}

export interface MetricResult {
  name: string;
  score: number;
  threshold: number;
  status: 'pass' | 'warning' | 'blocking';
  details?: any;
}

export interface QualityIssue {
  metric: string;
  severity: 'warning' | 'blocking';
  message: string;
  recommendation: string;
  affectedElements: string[];
}

// Phase1质量卡点：Figma数据提取完整性
export const Phase1QualityGate: QualityGateConfig = {
  phase: 1,
  name: 'Figma数据提取质量',
  requiredMetrics: [
    {
      name: 'figmaDataCompleteness',
      weight: 0.4,
      threshold: { blocking: 0.95, warning: 0.98 },
      calculator: async (output) => {
        const { informationIndex } = output;
        return informationIndex.processedNodes / informationIndex.totalNodes;
      }
    },
    {
      name: 'blueprintStructureValid',
      weight: 0.3,
      threshold: { blocking: 1.0, warning: 1.0 },
      calculator: async (output) => {
        const { blueprint } = output;
        const requiredFields = ['componentName', 'configurableProps', 'layoutStructure'];
        const hasAllFields = requiredFields.every(field => field in blueprint);
        const hasValidProps = blueprint.configurableProps?.length > 0;
        return hasAllFields && hasValidProps ? 1.0 : 0.0;
      }
    },
    {
      name: 'complexUIElementsCaptured',
      weight: 0.3,
      threshold: { blocking: 0.90, warning: 0.95 },
      calculator: async (output) => {
        const { designContext } = output;
        const complexTypes = ['INSTANCE', 'COMPONENT', 'FRAME'];
        const complexNodes = designContext.filter(node => complexTypes.includes(node.type));
        const processedComplexNodes = complexNodes.filter(node =>
          output.informationIndex.processedNodes.includes(node.id)
        );
        return complexNodes.length > 0 ? processedComplexNodes.length / complexNodes.length : 1.0;
      }
    }
  ],
  blockingThreshold: 0.90,
  warningThreshold: 0.95
};

// Phase2质量卡点：UI还原度和组件质量
export const Phase2QualityGate: QualityGateConfig = {
  phase: 2,
  name: 'UI还原度和组件质量',
  requiredMetrics: [
    {
      name: 'uiRestorationRate',
      weight: 0.4,
      threshold: { blocking: 0.95, warning: 0.98 },
      calculator: async (output) => {
        // 基于截图对比计算UI还原度
        return await calculateUIRestoration(output.component, output.figmaReference);
      }
    },
    {
      name: 'componentCompilable',
      weight: 0.2,
      threshold: { blocking: 1.0, warning: 1.0 },
      calculator: async (output) => {
        try {
          await compileComponent(output.component);
          return 1.0;
        } catch (error) {
          return 0.0;
        }
      }
    },
    {
      name: 'propsStructureValid',
      weight: 0.25,
      threshold: { blocking: 1.0, warning: 1.0 },
      calculator: async (output) => {
        const { component } = output;
        const propsValid = validatePropsStructure(component.props, output.blueprint.configurableProps);
        return propsValid ? 1.0 : 0.0;
      }
    },
    {
      name: 'informationLossAcceptable',
      weight: 0.15,
      threshold: { blocking: 0.80, warning: 0.90 },
      calculator: async (output) => {
        const { informationUsage } = output;
        const criticalLoss = informationUsage.lostElements.filter(
          element => element.criticality === 'high'
        );
        const totalCritical = informationUsage.criticalElements || 1;
        return (totalCritical - criticalLoss.length) / totalCritical;
      }
    }
  ],
  blockingThreshold: 0.95,
  warningThreshold: 0.98
};

// Phase3质量卡点：配置层完整性
export const Phase3QualityGate: QualityGateConfig = {
  phase: 3,
  name: '配置层设计质量',
  requiredMetrics: [
    {
      name: 'fieldCoverageRate',
      weight: 0.35,
      threshold: { blocking: 1.0, warning: 1.0 },
      calculator: async (output) => {
        const { fieldsConfig, componentProps } = output;
        const propsCount = Object.keys(componentProps).length;
        const fieldsCount = Object.keys(fieldsConfig).length;
        return fieldsCount / propsCount;
      }
    },
    {
      name: 'editFieldsConsistency',
      weight: 0.30,
      threshold: { blocking: 1.0, warning: 1.0 },
      calculator: async (output) => {
        const { editFields, fieldsConfig } = output;
        const editKeys = editFields.map(field => field.key);
        const fieldKeys = Object.keys(fieldsConfig);
        const consistentKeys = editKeys.filter(key => fieldKeys.includes(key));
        return consistentKeys.length / editKeys.length;
      }
    },
    {
      name: 'panelMappingValid',
      weight: 0.25,
      threshold: { blocking: 0.95, warning: 1.0 },
      calculator: async (output) => {
        const { editFields } = output;
        const belongToMappings = editFields.map(field => field.belongTo);
        const validMappings = belongToMappings.filter(belongTo =>
          isValidBelongToMapping(belongTo)
        );
        return validMappings.length / belongToMappings.length;
      }
    },
    {
      name: 'reuseStrategyOptimal',
      weight: 0.10,
      threshold: { blocking: 0.70, warning: 0.80 },
      calculator: async (output) => {
        const { panelReuseAnalysis } = output;
        const reuseRate = panelReuseAnalysis.reusedPanels / panelReuseAnalysis.totalPanels;
        return reuseRate;
      }
    }
  ],
  blockingThreshold: 0.90,
  warningThreshold: 0.95
};

// 质量卡点执行器
export class QualityGateRunner {
  private gates: Map<number, QualityGateConfig> = new Map();

  constructor() {
    this.gates.set(1, Phase1QualityGate);
    this.gates.set(2, Phase2QualityGate);
    this.gates.set(3, Phase3QualityGate);
  }

  async runGate(phase: number, phaseOutput: any): Promise<QualityGateResult> {
    const gate = this.gates.get(phase);
    if (!gate) {
      throw new Error(`Phase ${phase} 质量卡点配置未找到`);
    }

    const metricResults: MetricResult[] = [];
    const blockers: QualityIssue[] = [];
    const warnings: QualityIssue[] = [];

    // 执行所有质量指标检查
    for (const metric of gate.requiredMetrics) {
      const score = await metric.calculator(phaseOutput);
      const status = this.getMetricStatus(score, metric.threshold);

      metricResults.push({
        name: metric.name,
        score,
        threshold: metric.threshold.blocking,
        status,
        details: { weight: metric.weight }
      });

      // 生成问题和建议
      if (status === 'blocking') {
        blockers.push({
          metric: metric.name,
          severity: 'blocking',
          message: `${metric.name} 得分 ${score.toFixed(2)} 低于阻塞阈值 ${metric.threshold.blocking}`,
          recommendation: this.getMetricRecommendation(metric.name, score, phaseOutput),
          affectedElements: this.getAffectedElements(metric.name, phaseOutput)
        });
      } else if (status === 'warning') {
        warnings.push({
          metric: metric.name,
          severity: 'warning',
          message: `${metric.name} 得分 ${score.toFixed(2)} 低于警告阈值 ${metric.threshold.warning}`,
          recommendation: this.getMetricRecommendation(metric.name, score, phaseOutput),
          affectedElements: this.getAffectedElements(metric.name, phaseOutput)
        });
      }
    }

    // 计算综合得分
    const totalScore = this.calculateTotalScore(metricResults, gate.requiredMetrics);
    const success = blockers.length === 0 && totalScore >= gate.blockingThreshold;
    const canProceed = blockers.length === 0;

    return {
      phase,
      success,
      score: totalScore,
      metrics: metricResults,
      blockers,
      warnings,
      recommendations: this.generateRecommendations(blockers, warnings, phase),
      canProceed
    };
  }

  private getMetricStatus(score: number, threshold: { blocking: number; warning: number }): 'pass' | 'warning' | 'blocking' {
    if (score < threshold.blocking) return 'blocking';
    if (score < threshold.warning) return 'warning';
    return 'pass';
  }

  private calculateTotalScore(results: MetricResult[], metrics: QualityMetric[]): number {
    const weightedSum = results.reduce((sum, result, index) => {
      return sum + result.score * metrics[index].weight;
    }, 0);
    const totalWeight = metrics.reduce((sum, metric) => sum + metric.weight, 0);
    return weightedSum / totalWeight;
  }

  private getMetricRecommendation(metricName: string, score: number, phaseOutput: any): string {
    const recommendations = {
      figmaDataCompleteness: `检查 Figma MCP 连接状态，确保所有节点都被正确提取。当前完成度：${(score * 100).toFixed(1)}%`,
      blueprintStructureValid: `验证 blueprint.json 结构完整性，确保包含 componentName、configurableProps 和 layoutStructure`,
      uiRestorationRate: `UI还原度不足，需要检查组件样式映射。当前还原度：${(score * 100).toFixed(1)}%`,
      componentCompilable: `组件编译失败，检查 TypeScript 类型定义和导入语句`,
      fieldCoverageRate: `字段覆盖不完整，确保所有 Props 都在 FieldNode 中定义。覆盖率：${(score * 100).toFixed(1)}%`,
      editFieldsConsistency: `EditFields 与 FieldNode 不一致，检查字段键值对应关系`,
      panelMappingValid: `面板映射无效，检查 belongTo 分类是否正确`
    };

    return recommendations[metricName] || `${metricName} 需要进一步检查和优化`;
  }

  private getAffectedElements(metricName: string, phaseOutput: any): string[] {
    // 根据不同指标返回受影响的具体元素
    switch (metricName) {
      case 'uiRestorationRate':
        return phaseOutput.uiMapping?.differences || [];
      case 'fieldCoverageRate':
        return phaseOutput.missingFields || [];
      case 'editFieldsConsistency':
        return phaseOutput.inconsistentFields || [];
      default:
        return [];
    }
  }

  private generateRecommendations(blockers: QualityIssue[], warnings: QualityIssue[], phase: number): string[] {
    const recommendations = [];

    if (blockers.length > 0) {
      recommendations.push(`Phase ${phase} 存在 ${blockers.length} 个阻塞性问题，必须修复后才能继续：`);
      blockers.forEach(blocker => {
        recommendations.push(`- ${blocker.message}: ${blocker.recommendation}`);
      });
    }

    if (warnings.length > 0) {
      recommendations.push(`Phase ${phase} 存在 ${warnings.length} 个警告，建议优化：`);
      warnings.forEach(warning => {
        recommendations.push(`- ${warning.message}: ${warning.recommendation}`);
      });
    }

    return recommendations;
  }
}

// 辅助函数
async function calculateUIRestoration(component: any, figmaReference: any): Promise<number> {
  // 实现UI还原度计算逻辑
  // 可以通过截图对比、关键元素检查等方式实现
  return 0.95; // 示例返回值
}

async function compileComponent(component: any): Promise<boolean> {
  // 实现组件编译检查
  return true; // 示例返回值
}

function validatePropsStructure(componentProps: any, blueprintProps: any): boolean {
  // 实现Props结构验证
  return true; // 示例返回值
}

function isValidBelongToMapping(belongTo: string): boolean {
  // 白名单来源：Resources/knowledge-base/belongTo-whitelist.json
  const validMappings = [
    'header',
    'eventReportSetting',
    'basicInfo',
    'groupSetting',
    'publishInfo',
    'titleStyle',
    'staticTextStyle',
    'cardStyle',              // 注意：不是 chartStyle
    'componentStyle',
    'contentStyle',
    'dashboardThemeTypeMuti',
    'floorStyle',
    'upLoadImg',
    'accountInfoStyle',
    'countdownStyle',
    'separatorStyle',
    'activeBtnStyle',
    'menuStyle',
    'publicDashInfo'
  ];

  // 检测无效值
  const invalidValues = ['chartStyle', 'dataConfig', 'themeStyle', 'tabStyle', 'trendDataConfig'];
  if (invalidValues.includes(belongTo)) {
    console.error(`ERR_INVALID_BELONGTO: "${belongTo}" 不是有效的 belongTo 值，请检查 belongTo-whitelist.json`);
    return false;
  }

  return validMappings.includes(belongTo);
}

export const qualityGateRunner = new QualityGateRunner();
